<script setup>
import { h, onMounted, ref, resolveDirective, withDirectives } from 'vue'

import {
    useMessage,
    NButton, NForm, NFormItem, NInput, NInputNumber, NPopconfirm, NTreeSelect, NTag, NSwitch, NFlex,
    NAvatar, NSelect, NImage
} from 'naive-ui'

import CommonPage from '@/components/page/CommonPage.vue'
import QueryBarItem from '@/components/query-bar/QueryBarItem.vue'
import CrudModal from '@/components/table/CrudModal.vue'
import CrudTable from '@/components/table/CrudTable.vue'
import TheIcon from '@/components/icon/TheIcon.vue'
import { getToken } from '@/utils'
import { renderIcon } from '@/utils'
import {useCRUD} from '@/composables'
// import { loginTypeMap, loginTypeOptions } from '@/constant/data'
import api from '@/api'

defineOptions({name: '小程序配置开关'})

const $table = ref(null)
const queryItems = ref({})
const vPermission = resolveDirective('permission')
const base_path = import.meta.env.VITE_BASE

const {
  modalVisible,
  modalTitle,
  modalLoading,
  handleSave,
  modalForm,
  modalFormRef,
  handleEdit,
  handleDelete,
  handleAdd,
} = useCRUD({
  name: '小程序配置开关',
  initForm: {},
  doCreate: api.createMiniSettings,
  doUpdate: api.updateMiniSettings,
  doDelete: api.deleteMiniSettings,
  refresh: () => $table.value?.handlerefresh(),
})
const isDisabled = ref(false)
const data = reactive({

});


onMounted(() => {
  $table.value?.handleSearch()
})

async function addDepts() {
  isDisabled.value = false
  handleAdd()
}

// 修改用户禁用状态
async function handleUpdateDisable(row) {
  if (!row.id) return
  row.publishing = true
  row.is_active = row.is_active === false ? true : false
  row.publishing = false
  try {
    await api.updateMiniSettings(row)
    $message?.success(row.is_active ? '已启用' : '已禁用')
    $table.value?.handlerefresh()
  } catch (err) {
    // 有异常恢复原来的状态
    row.is_active = row.is_active === false ? true : false
  } finally {
    row.publishing = false
  }
}


const columns = [
  {
    title: 'ID',
    key: 'id',
    width: 40,
    align: 'center',
    ellipsis: {tooltip: true},
  },
  {
    title: '名称',
    key: 'name',
    width: 'auto',
    align: 'center',
    ellipsis: {tooltip: true},
    fixed: 'left',
  },
 {
    title: '值',
    key: 'set_value',
    width: 'auto',
    align: 'center',
    ellipsis: {tooltip: true},
    fixed: 'left',
  },

  {
    title: '状态',
    key: 'is_active',
    width: '100',
    align: 'center',
    fixed: 'right',
    render(row) {
      return h(NSwitch, {
        size: 'small',
        rubberBand: false,
        value: row.is_active,
        loading: !!row.publishing,
        checkedValue: true,
        uncheckedValue: false,
        onUpdateValue: () => handleUpdateDisable(row),
      })
    },
  },
  {
    title: '创建时间',
    key: 'created_at',
    align: 'center',
    width: 'auto',
    ellipsis: {tooltip: true},
  },
  {
    title: '操作',
    key: 'actions',
    width: 'auto',
    align: 'center',
    fixed: 'right',
    render(row) {
      return [
        withDirectives(
            h(
                NButton,
                {
                  size: 'small',
                  type: 'primary',
                  style: 'margin-right: 8px;',
                  onClick: () => {
                    handleEdit(row)
                  },
                },
                {
                  default: () => '编辑',
                  icon: renderIcon('material-symbols:edit', {size: 16}),
                }
            ),
            [[vPermission, 'post/api/mini/settings/update']]
        ),
        // h(
        //     NPopconfirm,
        //     {
        //       onPositiveClick: () => handleDelete({data_id: row.id}, false),
        //       onNegativeClick: () => {
        //       },
        //     },
        //     {
        //       trigger: () =>
        //           withDirectives(
        //               h(
        //                   NButton,
        //                   {
        //                     size: 'small',
        //                     type: 'error',
        //                   },
        //                   {
        //                     default: () => '删除',
        //                     icon: renderIcon('material-symbols:delete-outline', {size: 16}),
        //                   }
        //               ),
        //               [[vPermission, 'delete/api/mini/settings/delete']]
        //           ),
        //       default: () => h('div', {}, '确定删除该数据吗?'),
        //     }
        // ),
      ]
    },
  },
]
const validateAddUser = {
    name: [
        {
            required: true,
            message: '请输入名称',
            trigger: ['input', 'blur', 'change'],
        },
    ],
}
</script>

<template>
  <!-- 业务页面 -->
  <CommonPage show-footer title="小程序配置开关">
    <template #action>
      <div>
        <NButton v-permission="'post/api/mini/settings/create'" class="float-right mr-15" type="primary"
                 @click="addDepts">
          <TheIcon icon="material-symbols:add" :size="18" class="mr-5"/>
          新建配置
        </NButton>
      </div>
    </template>
    <!-- 表格 -->
    <CrudTable ref="$table" v-model:query-items="queryItems" :columns="columns" :get-data="api.getMiniSettings">
      <template #queryBar>
        <QueryBarItem label="名称" :label-width="80">
          <NInput v-model:value="queryItems.name" clearable type="text" placeholder="请输入名称"
                  @keypress.enter="$table?.handleSearch()"/>
        </QueryBarItem>
      </template>
    </CrudTable>

    <!-- 新增/编辑 弹窗 -->
    <CrudModal v-model:visible="modalVisible" :title="modalTitle" :loading="modalLoading" @save="handleSave"
               >
      <NForm ref="modalFormRef" label-placement="left" label-align="left" :label-width="80" :model="modalForm"
             :rules="validateAddUser">
          <NFormItem label="名称" path="name">
            <NInput v-model:value="modalForm.name" clearable placeholder="请输入名称"/>
          </NFormItem>
        <NFormItem label="值" path="set_value">
            <NInput v-model:value="modalForm.set_value" clearable placeholder="请输入值"/>
          </NFormItem>
      </NForm>
    </CrudModal>
  </CommonPage>
</template>
